<template>
  <el-dialog
    v-model="visible"
    title="添加SKU"
    width="1200"
    draggable
    @close="close"
    :z-index="2000"
  >
    <div class="search mb-4">
      <multi-input
        v-model="form.sku"
        placeholder="SKU,批量搜索"
        class="w-50 mr-4"
      ></multi-input>
      <multi-input
        v-model="form.custom_sku"
        placeholder="自定义SKU,批量搜索"
        class="w-50 mr-4"
      ></multi-input>
      <el-input
        v-model="form.sku_cn_title"
        placeholder="产品中文名称"
        clearable
        class="w-40 mr-4"
      />
      <el-button type="primary" @click="search()">查询</el-button>
    </div>
    <vxe-table
      ref="tableRef"
      :data="tableData"
      height="530"
      @checkbox-change="checkboxChangeEvent"
      @checkbox-all="checkboxChangeEvent"
      :checkbox-config="checkboxConfig"
      :loading="loading"
      resizable
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column field="attr_img" title="图片" width="75">
        <template #default="{ row }">
          <el-image
            :src="row.attr_img_watermark || row.attr_img"
            width="72"
            height="72"
            @contextmenu.prevent
          ></el-image>
        </template>
      </vxe-column>
      <vxe-column field="sku_cn_title" title="产品名称" width="220">
        <template #default="{ row }">
          <el-tooltip
            class="box-item"
            effect="dark"
            :content="row.sku_cn_title"
            placement="top-start"
          >
            <vText :value="row.sku_cn_title" :line="3" copy></vText>
          </el-tooltip>
        </template>
      </vxe-column>
      <vxe-column field="spu" title="SPU" width="120"></vxe-column>
      <vxe-column field="sku" title="SKU/自定义" width="180">
        <template #default="{ row }">
          <div>{{ row.sku }}</div>
          <div>{{ row.custom_sku }}</div>
        </template>
      </vxe-column>
      <vxe-column field="specification" title="规格">
        <template #default="{ row }">
          <template v-if="row.specification">
            <div v-for="(item, index) in row.specification" :key="index">
              {{ item.name }}
            </div>
          </template>
          <template v-else>--</template>
        </template>
      </vxe-column>
      <vxe-column field="sku_product_type_text" title="产品类型"> </vxe-column>
      <vxe-column field="supplier_quotation" title="采购未税报价(CNY)">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price"
            :value="row.supplier_quotation"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column field="purchase_untaxed_price" title="采购未税价">
        <template #default="{ row }">
          <dataAuthority
            auth="purchase_untaxed_price"
            :value="row.purchase_untaxed_price"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column field="unit_price_tax" title="采购含税价">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price_tax"
            :value="row.unit_price_tax"
          ></dataAuthority>
        </template>
      </vxe-column>
    </vxe-table>
    <div>
      <vxe-pager
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="totalResult"
        :page-sizes="[10, 20, 100]"
        @page-change="pageChange"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'Jump',
          'PageCount',
          'NextPage',
          'NextJump',
          'Sizes',
          'Total',
        ]"
      >
      </vxe-pager>
    </div>
    <template #footer>
      <div class="flex justify-between items-center">
        <div class="text-sm">
          已选择 <span class="text-blue-500">{{ records.length }}</span> 条
        </div>
        <div>
          <el-button @click="close">取消</el-button>
          <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="AdvancedSearch" lang="jsx">
import { nextTick, reactive, ref, toRefs } from "vue";
import { queryCombinationSkuList } from "./api";
import { ElMessage, ElMessageBox } from "element-plus";

const emits = defineEmits(["assign"]);

const props = defineProps({
  checkedList: {
    type: Array,
    default: () => [],
  },
  is_type: {
    type: Number,
    default: 0, // default 1 商品新增编辑选择组合SKU
  },
});

const { checkedList, is_type } = toRefs(props);

const data = reactive({
  visible: false,
  loading: false,
  form: {
    sku: "",
    custom_sku: "",
    sku_cn_title: "",
  },
  tableData: [],
  records: [],
  totalResult: 0,
  currentPage: 1,
  pageSize: 10,
  type: "", // 1 组合sku
});
const {
  visible,
  loading,
  form,
  tableData,
  records,
  totalResult,
  currentPage,
  pageSize,
  type,
} = toRefs(data);

const checkboxConfig = reactive({
  labelField: "name",
  checkMethod({ row }) {
    return !props.checkedList.find((i) => i.id == row.id);
  },
});

const open = (val) => {
  type.value = val;
  visible.value = true;
  nextTick(() => {
    search();
  });
};
const close = () => {
  totalResult.value = 0;
  currentPage.value = 1;
  pageSize.value = 10;
  visible.value = false;
};

const tableRef = ref();
const checkboxChangeEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    records.value = $table.getCheckboxRecords();
  }
};

const pageChange = () => {
  search({ pageNum: currentPage.value, pageSize: pageSize.value });
}; //page number change, update currentPage and totalResult 的回调函数，可以在页面加载更

const search = async (data = {}) => {
  records.value = [];
  loading.value = true;
  try {
    const requestFun = type.value == 1 ? queryCombinationSkuList : querySkuList;
    const res = await requestFun({
      ...form.value,
      ...data,
    });
    tableData.value = res.data;
    totalResult.value = res.total;
  } catch (e) {
    throw Error(e);
  } finally {
    loading.value = false;
  }
};

const save = async () => {
  if (records.value.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }

  if (is_type.value) {
    const difference = findFirstDifference(checkedList.value, records.value);
    if (difference && difference.length) {
      return ElMessageBox({
        title: "组合SKU重复",
        message: <div>{difference.map((d) => h("p", null, d))}</div>,
      });
    }
  }
  emits("assign", records.value);
  close();
};

const findFirstDifference = (arr1, arr2) => {
  const differences = [];
  for (const obj1 of arr1) {
    for (const obj2 of arr2) {
      const sku1 = obj1.combination_sku_info?.sku;
      const sku2 = obj2.sku;
      // const difference = areObjectsDifferent(obj3, obj4)
      if (sku1 == sku2) {
        differences.push(sku1 + "已存在,请重新选择");
      }
    }
  }
  return differences;
};

defineExpose({ open });
</script>
